///<reference path="../init.d.ts"/>
// 观察者模式对象
let observer = (function () {
  // 私有变量
  let _messages: anyObj = {}

  return {
    regist (eventName: string, callback: Function) {
      if (!_messages.hasOwnProperty(eventName)) {
        _messages[ eventName ] = [ callback ]
      } else {
        _messages[ eventName ].push(callback)
      }
    },
    fire (eventName: string, args: any = {}) {
      if (!_messages[ eventName ]) return
      let events = {eventName, args}
        , i = 0
        , len = _messages[ eventName ].length;
      for (; i < len; i++) {
        _messages[ eventName ][ i ].call(this, events)
      }

    },
    remove (eventName: string, callBack: Function) {
      if (_messages[ eventName ] instanceof Array && _messages[ eventName ].length > 0) {
        for (let i = 0, len = _messages[ eventName ].length; i < len; i++) {
          if (_messages[ eventName ][ i ] === callBack) {
            _messages[ eventName ].splice(i, 1)
            break
          }
        }
      }
    }
  }
})()



export default observer
